<template>
  <el-dialog
    title="Menu Edit"
    :visible.sync="dialogVisible"
    width="25%"
    @close="handleClose"
  >
    <el-tree
      ref="tree"
      :data="data"
      show-checkbox
      node-key="roleId"
      default-expand-all
      :default-checked-keys="checked"
      :props="defaultProps"
    />

    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">Cancel</el-button>
      <el-button type="primary" @click="save">Save</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getRoleMenu, saveMenu } from '@/api/role'
import { menuRoutes } from '@/router'

export default {
  data() {
    return {
      dialogVisible: false,
      roleId: '',
      data: [{
        name: 'Library',
        roleId: 'A0',
        children: menuRoutes
      }],
      checked: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  methods: {
    async save() {
      await saveMenu({
        roleId: this.roleId,
        menus: this.$refs.tree.getCheckedKeys()
      })
      this.$message({
        type: 'success',
        message: 'menu role save success'
      })
      this.handleClose()
    },

    handleClose() {
      this.dialogVisible = false
    },

    async show(id) {
      if (id) {
        this.roleId = id
        this.checked = await getRoleMenu()
      }
      this.dialogVisible = true
    }
  }
}
</script>
